<template>
  <div class="orders-container">
    <div class="search-bar">
      <div class="search-container">
        <el-input v-model="searchOrderNo" placeholder="订单号" clearable style="width: 180px;" />
        <el-date-picker
          v-model="searchDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 320px;"
        />
        <el-input v-model="searchReceiver" placeholder="收货人" clearable style="width: 150px;" />
        <el-select v-model="searchStatus" placeholder="订单状态" clearable style="width: 120px;">
          <el-option label="全部" :value="null" />
          <el-option label="待付款" :value="0" />
          <el-option label="待发货" :value="1" />
          <el-option label="已发货" :value="2" />
          <el-option label="已完成" :value="3" />
        </el-select>
        <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
        <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
      </div>
    </div>

    <!-- 订单列表 -->
    <el-table
      v-loading="loading"
      :data="orderList"
      border
      style="width: 100%"
      :fit="false"
    >
      <el-table-column prop="orderNo" label="订单号" width="200" />
      <el-table-column prop="createTime" label="下单时间" width="200" />
      <el-table-column prop="receiverName" label="收货人" width="140" />
      <el-table-column prop="receiverPhone" label="联系电话" width="160" />
      <el-table-column prop="totalAmount" label="商品总价" width="120">
        <template #default="scope">
          ¥{{ scope.row.totalAmount.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="促销优惠" width="120">
        <template #default="scope">
          <span v-if="scope.row.promotionAmount && scope.row.promotionAmount > 0" class="discount-amount">
            -¥{{ scope.row.promotionAmount.toFixed(2) }}
            <el-tooltip content="满100减20优惠已应用" placement="top" v-if="scope.row.totalAmount >= 100">
              <el-tag size="small" type="danger" class="discount-tag">满减</el-tag>
            </el-tooltip>
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="实付金额" width="120">
        <template #default="scope">
          <span class="pay-amount">¥{{ scope.row.payAmount.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="订单状态" width="140">
        <template #default="scope">
          <el-tag :type="getOrderStatusType(scope.row.status)">
            {{ getOrderStatusName(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="scope">
          <div class="operation-buttons">
            <el-button size="small" @click="viewOrderDetail(scope.row.orderNo)">查看</el-button>
            <el-button
              v-if="scope.row.status === 1"
              size="small"
              type="primary"
              @click="openShipDialog(scope.row)"
            >
              发货
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      v-model="orderDetailVisible"
      width="70%"
    >
      <div v-loading="detailLoading">
        <div v-if="orderDetail">
          <div class="order-info">
            <h3>基本信息</h3>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="订单号">{{ orderDetail.order.orderNo }}</el-descriptions-item>
              <el-descriptions-item label="下单时间">{{ orderDetail.order.createTime }}</el-descriptions-item>
              <el-descriptions-item label="订单状态">
                <el-tag :type="getOrderStatusType(orderDetail.order.status)">
                  {{ getOrderStatusName(orderDetail.order.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="支付时间" v-if="orderDetail.order.payTime">
                {{ orderDetail.order.payTime }}
              </el-descriptions-item>
              <el-descriptions-item label="发货时间" v-if="orderDetail.order.deliveryTime">
                {{ orderDetail.order.deliveryTime }}
              </el-descriptions-item>
              <el-descriptions-item label="物流单号" v-if="orderDetail.order.trackingNo">
                {{ orderDetail.order.trackingNo }}
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="shipping-info">
            <h3>收货信息</h3>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="收货人">{{ orderDetail.order.receiverName }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ orderDetail.order.receiverPhone }}</el-descriptions-item>
              <el-descriptions-item label="收货地址">{{ orderDetail.order.receiverAddress }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="order-items">
            <h3>商品信息</h3>
            <el-table :data="orderDetail.orderItems" border style="width: 100%">
              <el-table-column prop="productName" label="商品名称" />
              <el-table-column prop="productPrice" label="单价" width="120">
                <template #default="scope">
                  ¥{{ scope.row.productPrice.toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="100" />
              <el-table-column label="小计" width="120">
                <template #default="scope">
                  ¥{{ (scope.row.productPrice * scope.row.quantity).toFixed(2) }}
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="order-summary">
            <h3>订单金额</h3>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="商品总价">¥{{ orderDetail.order.totalAmount.toFixed(2) }}</el-descriptions-item>
              <el-descriptions-item label="促销优惠" v-if="orderDetail.order.promotionAmount && orderDetail.order.promotionAmount > 0">
                <span class="discount-amount">-¥{{ orderDetail.order.promotionAmount.toFixed(2) }}</span>
                <el-tag size="small" type="danger" class="discount-tag" v-if="orderDetail.order.totalAmount >= 100">满减</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="实付金额">¥{{ orderDetail.order.payAmount.toFixed(2) }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 评价信息区域 -->
          <div v-if="orderDetail.order.status === 3 && orderReview" class="order-review">
            <h3>用户评价</h3>
            <el-card class="review-card">
              <div class="review-rating">
                <span class="rating-label">评分：</span>
                <el-rate
                  v-model="orderReview.rating"
                  disabled
                  :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                  :texts="['很差', '较差', '一般', '不错', '很好']"
                  show-text
                />
              </div>
              <div class="review-content">
                <span class="content-label">评价内容：</span>
                <p class="content-text">{{ orderReview.content }}</p>
              </div>
              <div class="review-time">
                <span>评价时间：{{ formatDate(orderReview.createTime) }}</span>
              </div>
            </el-card>
          </div>

          <div class="order-actions" v-if="orderDetail.order.status === 1">
            <el-button type="primary" @click="openShipDialog(orderDetail.order)">发货</el-button>
          </div>
        </div>
        <div v-else class="no-data">
          <p>订单数据加载失败</p>
        </div>
      </div>
    </el-dialog>

    <!-- 发货对话框 -->
    <el-dialog
      title="订单发货"
      v-model="shipDialogVisible"
      width="40%"
    >
      <el-form :model="shipForm" label-width="100px">
        <el-form-item label="订单号">
          <span>{{ shipForm.orderNo }}</span>
        </el-form-item>
        <el-form-item label="物流单号">
          <el-input v-model="shipForm.trackingNo" placeholder="请输入物流单号（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShip" :loading="shipLoading">确认发货</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getMerchantOrders, getMerchantOrderDetail, shipOrder, updateOrderStatus, getOrderReview } from '@/api/merchant'

const route = useRoute()
const router = useRouter()

// 订单列表数据
const orderList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索条件
const searchOrderNo = ref('')
const searchDateRange = ref([])
const searchReceiver = ref('')
const searchStatus = ref(null)

// 订单详情数据
const orderDetailVisible = ref(false)
const orderDetail = ref(null)
const detailLoading = ref(false)
const orderReview = ref(null)

// 发货表单数据
const shipDialogVisible = ref(false)
const shipLoading = ref(false)
const shipForm = reactive({
  orderNo: '',
  trackingNo: ''
})

// 获取订单列表
const fetchOrderList = async () => {
  loading.value = true
  try {
    const params = {
      orderNo: searchOrderNo.value,
      receiverName: searchReceiver.value,
      status: searchStatus.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }

    // 添加日期范围
    if (searchDateRange.value && searchDateRange.value.length === 2) {
      params.startDate = searchDateRange.value[0]
      params.endDate = searchDateRange.value[1]
    }

    const response = await getMerchantOrders(params)
    if (response.code === 200) {
      orderList.value = response.data.records
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取订单详情
const fetchOrderDetail = async (orderNo) => {
  detailLoading.value = true
  orderDetail.value = null

  try {
    const response = await getMerchantOrderDetail(orderNo)
    if (response.code === 200) {
      orderDetail.value = response.data

      // 如果订单状态为已完成，检查是否有评价
      if (orderDetail.value.order.status === 3 && orderDetail.value.orderItems.length > 0) {
        const firstItem = orderDetail.value.orderItems[0]
        fetchOrderReview(orderDetail.value.order.orderNo, firstItem.productId)
      } else {
        orderReview.value = null
      }
    } else {
      ElMessage.error(response.message || '获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  } finally {
    detailLoading.value = false
  }
}

// 查看订单详情
const viewOrderDetail = (orderNo) => {
  fetchOrderDetail(orderNo)
  orderDetailVisible.value = true
}

// 打开发货对话框
const openShipDialog = (order) => {
  shipForm.orderNo = order.orderNo
  shipForm.trackingNo = ''
  shipDialogVisible.value = true
}

// 确认发货
const confirmShip = async () => {
  shipLoading.value = true
  try {
    const response = await shipOrder(shipForm.orderNo, shipForm.trackingNo)
    if (response.code === 200) {
      ElMessage.success('发货成功')
      shipDialogVisible.value = false

      // 模拟更新本地数据
      const orderToUpdate = orderList.value.find(order => order.orderNo === shipForm.orderNo)
      if (orderToUpdate) {
        orderToUpdate.status = 2 // 更新为已发货状态
        orderToUpdate.trackingNo = shipForm.trackingNo || '无'
        orderToUpdate.deliveryTime = new Date().toISOString()
      }

      // 如果订单详情对话框打开，也更新详情数据
      if (orderDetailVisible.value && orderDetail.value && orderDetail.value.order.orderNo === shipForm.orderNo) {
        orderDetail.value.order.status = 2
        orderDetail.value.order.trackingNo = shipForm.trackingNo || '无'
        orderDetail.value.order.deliveryTime = new Date().toISOString()
      }
    } else {
      ElMessage.error(response.message || '发货失败')
    }
  } catch (error) {
    console.error('发货失败:', error)
    ElMessage.error('发货失败')
  } finally {
    shipLoading.value = false
  }
}

// 获取订单状态名称
const getOrderStatusName = (status) => {
  switch (status) {
    case 0: return '待付款'
    case 1: return '待发货'
    case 2: return '已发货'
    case 3: return '已完成'
    default: return '未知状态'
  }
}

// 获取订单评价
const fetchOrderReview = async (orderNo, productId) => {
  try {
    const response = await getOrderReview(orderNo, productId)
    if (response.code === 200) {
      orderReview.value = response.data
      console.log('获取到订单评价:', orderReview.value)
    } else if (response.code === 404) {
      // 评价不存在，这是正常情况，不是错误
      console.log('订单尚未评价')
      orderReview.value = null
    } else {
      orderReview.value = null
    }
  } catch (error) {
    console.error('获取订单评价失败:', error)
    orderReview.value = null
  }
}

// 获取订单状态对应的标签类型
const getOrderStatusType = (status) => {
  switch (status) {
    case 0: return 'warning'
    case 1: return 'danger'
    case 2: return 'primary'
    case 3: return 'success'
    default: return 'info'
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchOrderList()
}

// 重置搜索
const resetSearch = () => {
  searchOrderNo.value = ''
  searchDateRange.value = []
  searchReceiver.value = ''
  searchStatus.value = null
  currentPage.value = 1
  fetchOrderList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchOrderList()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchOrderList()
}

// 页面加载时获取数据
onMounted(() => {
  fetchOrderList()
})
</script>

<style scoped>
.orders-container {
  padding: 20px;
}

.search-bar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.order-info,
.shipping-info,
.order-items,
.order-summary,
.order-review {
  margin-bottom: 20px;
}

.order-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #909399;
}

/* 评价区域样式 */
.review-card {
  margin-top: 10px;
}

.review-rating {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.rating-label {
  margin-right: 10px;
  font-weight: 500;
  color: #606266;
}

.review-content {
  margin-bottom: 15px;
}

.content-label {
  font-weight: 500;
  color: #606266;
  display: block;
  margin-bottom: 8px;
}

.content-text {
  background-color: #f9f9f9;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #eee;
  margin: 0;
  color: #333;
}

.review-time {
  text-align: right;
  color: #909399;
  font-size: 12px;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  flex-direction: column;
  gap: 5px;
  align-items: center;
}

.operation-buttons .el-button {
  margin: 0;
  padding: 4px 8px;
  font-size: 12px;
}

/* 折扣金额样式 */
.discount-amount {
  color: #f56c6c;
  font-weight: bold;
}

.discount-tag {
  margin-left: 8px;
  transform: scale(0.8);
}

.pay-amount {
  font-weight: bold;
  color: #f56c6c;
}
</style>
